﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace scomA2Proj
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            //Tie the richtextbox to the static class
            ConsoleUtil.RichTextBox = this.rtf_consoleOutput;
            //Make output console readonly
            rtf_consoleOutput.ReadOnly = true;
            rtf_consoleOutput.BackColor = Color.White;
            rtf_consoleOutput.Cursor = Cursors.Arrow;
            rtf_consoleOutput.Enter += rtf_consoleOutput_Enter;
        }
        private void rtf_consoleOutput_Enter(object sender, EventArgs e)
        {
            //just put focus elsewhere when you click on rtf.
            label1.Focus();
        }

        private void b_run_Click(object sender, EventArgs e)
        {

            b_run.Enabled = false;
            Stopwatch totalTime = new Stopwatch();
            totalTime.Restart();
            int numPriceCut = (int)nud_numPriceCut.Value;
            int numRetailers = (int)nud_numRetailers.Value;
            int numBufferCells = (int)nud_numBufferCells.Value;
            MulticellBuffer farmBuffer = new MulticellBuffer(numBufferCells);
            ChickenFarm cf = new ChickenFarm(farmBuffer, numRetailers, numPriceCut );
            Retailer[] retailers = new Retailer[numRetailers];

            Random r = new Random();
            //startretailer thread
            Thread[] retailThread = new Thread[numRetailers];
            for (int i = 0; i < numRetailers; i++)
            {
                retailers[i] = new Retailer(farmBuffer, r.Next(10000, 20000));
                
                retailThread[i] = new Thread(new ThreadStart(retailers[i].retailerStuff));
                retailThread[i].Start();
                cf.registerRetailer(retailers[i]);
                OrderProcessingThread.orderComplete += new OrderCompleteEvent(retailers[i].OrderCompleteEventHandler);
            }
            //subscribe to events
            
            //start chickenFarm Thread
            Thread chickenFarmThread = new Thread(new ThreadStart(cf.runChickenFarm));
            chickenFarmThread.Start();

            chickenFarmThread.Join();
            for (int i = 0; i < numRetailers; i++)
            {
                retailers[i].stop();
            }

            totalTime.Stop();
            ConsoleUtil.AppendLine(" Total Exe Time: " + totalTime.Elapsed);
            b_run.Enabled = true;
        }

        private void b_clearOutput_Click(object sender, EventArgs e)
        {
            rtf_consoleOutput.Clear();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        } 
    }
}
